<template>
  <div>
    <el-dialog v-if="modalShow" title="现场咨询" :visible.sync="modalShow" class="two-columns" width="60%" :before-close="modalClose" center>
      <UserInfo :info-id="ruleForm.customerId" />
      <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" :rules="rules" label-width="100px" style="padding-bottom: 30px" class="demo-ruleForm">
        <el-row type="flex">
          <el-row style="width:50%">
            <el-form-item style="width: 100%" label="就诊类型：" prop="treatType">
              <dictionary-selector class="el-select-y" code="swan_front_jzlx" :value.sync="ruleForm.treatType" />
            </el-form-item>
            <!-- 3.1改 -->
            <el-form-item label="咨询分类：" style="width: 100%" prop="consultTypeName">
              <el-select v-model="ruleForm.consultTypeName" class="el-select-y" placeholder="请选择" @change="selectAttendingDoctor">
                <el-option v-for="(item, i) of demands" :key="i" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <!-- 3.1改 -->
            <el-form-item label="主治医生：" style="width: 100%" prop="attendingDoctor">
              <el-select v-model="ruleForm.attendingDoctor" class="el-select-y" placeholder="请选择" @change="selectAttendingDoctor">
                <el-option v-for="item of attendingDoctors" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="意向项目：">
              <el-autocomplete
                v-model="state"
                popper-class="my-autocomplete"
                :fetch-suggestions="querySearch"
                placeholder="请输入名称或拼音码"
                style="width:100%"
                @select="handleSelect"
              >
                <i
                  slot="suffix"
                  class="el-input__icon"
                  @click="handleIconClick"
                />
                <template slot-scope="{ item }">
                  <div class="name" @click="handleProduct(item)">{{ item.name }}<el-button type="text">添加</el-button></div>
                </template>
              </el-autocomplete>
              <ul style="line-height: 30px;">
                <li v-for="(item,i) in ruleForm.sbDtos" :key="i">
                  <span style="width:85%;display:inline-block">{{ item.intentionProject }}</span>
                  <el-popconfirm
                    title="确定删除吗？"
                    @confirm="deteleProduct(item)"
                  >
                    <el-button slot="reference" type="text" style="text-align: right;">删除</el-button>
                  </el-popconfirm>
                </li>
              </ul>
            </el-form-item>
          </el-row>
          <el-row style="width:50%;">
            <el-form-item style="width: 100%" label="需求1：" prop="oneDemand">
              <el-cascader
                v-model="ruleForm.oneDemand"
                :options="options"
                :props="propsOption"
                style="width:100%"
                @change="handleChange($event,'1')"
              />
            </el-form-item>
            <el-form-item style="width: 100%" label="需求2：" prop="towDemand">
              <el-cascader
                v-model="ruleForm.towDemand"
                :options="options"
                :props="propsOption"
                style="width:100%"
                @change="handleChange($event,'2')"
              />
            </el-form-item>
            <el-form-item style="width: 100%" label="需求3：" prop="threeDemand">
              <el-cascader
                v-model="ruleForm.threeDemand"
                :options="options"
                :props="propsOption"
                style="width:100%"
                @change="handleChange($event,'3')"
              />
            </el-form-item>
          </el-row>
        </el-row>
        <el-row style="width: 100%">
          <el-form-item label="咨询情况：" prop="advisoryInfo">
            <div class="editor box">
              <editor-content id="ditor" class="editor__content" :editor="editor" />
            </div>
          </el-form-item>
          <el-form-item label="附件说明：" prop="attachUrl">
            <el-upload :action="uploadUrl" :class="ruleForm.attachUrl ? '' : 'is-true'" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="fileRemove" :before-remove="handleRemove" :on-success="handleList">
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="医生意见：" prop="opinion">
              <el-radio v-model="ruleForm.opinion" label="未见医生" />
              <el-radio v-model="ruleForm.opinion" label="已见医生" />
            </el-form-item>
          </el-col>
          <el-col v-if="ruleForm.opinion==='已见医生'" :span="12">
            <el-form-item label="面诊医生：" prop="faceDoctor" style="width: 100%">
              <el-select v-model="ruleForm.faceDoctor" class="el-select-y" placeholder="请选择" @change="selectAttendingFaceDoctor">
                <el-option v-for="item of attendingDoctors" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            <!-- 点击后，先保存当前咨询记录，然后向主治医生发出面诊任务  -->
            <!-- <el-button @click="addConsultation">发起面诊</el-button>
              {{
                interviewTaskDate === "" ? "" : "发起时间: " + interviewTaskDate
              }} -->
            </el-form-item>
          </el-col>
          <!-- <el-form-item label="面诊意见" prop="opinion">
              <div>
                <textarea
                  id=""
                  v-model="ruleForm.opinion"
                  name=""
                  cols="30"
                  rows="10"
                  class="box"
                  style="resize: none"
                />
              </div>
              <el-button type="text"> 更新 </el-button>
            </el-form-item> -->
          <el-col>
            <el-form-item label="咨询结果：" prop="result">
              <el-radio v-model="ruleForm.result" label="成交" />
              <el-radio v-model="ruleForm.result" label="不成交" />
            </el-form-item>
          </el-col>
          <!-- <el-col>
            <el-form-item v-if="ruleForm.result === '成交'" label="" prop="handPlane">
              <el-button class="color" @click="createBill()">去开单</el-button>
              <el-button class="color" @click="createRecharge()">去充值</el-button>
            </el-form-item>
          </el-col> -->
          <div v-if="ruleForm.result === '不成交'">
            <el-col>
              <el-form-item style="width: 100%" label="不成交原因：" prop="loseReasons">
                <el-checkbox-group v-model="ruleForm.loseReasons">
                  <el-checkbox v-for="(item,i) in type" :key="i" :label="item.name" name="type" />
                </el-checkbox-group>
              <!-- <dictionary-selector code="swan_front_bcjyy" :value.sync="ruleForm.loseReasons" /> -->
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item style="width: 100%" label="设定回访：" prop="simpleDtoList">
                <el-row v-for="(item,i) in ReturnVisitRules" :key="i">
                  <el-col>
                    默认计划{{ i+1 }}：第{{ item.returnDay }}天
                  </el-col>
                <!-- <el-col>
                    回访时间：{{ item.rebackTime }} 回访人：{{ item.returnName }}
                  </el-col> -->
                </el-row>
                <ul>
                  <li v-for="(items,i) in plainData" :key="i">
                    <span>
                      计划{{ i+1+ReturnVisitRules.length }}
                    </span>
                    <el-row type="flex" style="width:600px">
                      <el-col :span="11">
                        <el-form-item label="回访日期：" prop="rebackTime">
                          <el-date-picker v-model="items.rebackTime" :picker-options="pickerOptions" type="date" placeholder="选择日期" value-format="yyyy-MM-dd hh:m:mm" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item label="回访人：" prop="returnId">
                          <el-select v-model="items.returnId" class="el-select-y" placeholder="选择回访人" @change="rebackManChangeValue($event,i)">
                            <el-option v-for="item of ruleForm.getAllUsr" :key="item.id" :label="item.usrName" :value="item.id" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="2" :offset="1">
                        <el-popconfirm
                          title="确定删除吗？"
                          @confirm="deletePlain(i)"
                        >
                          <el-button slot="reference" type="text">删除</el-button>
                        </el-popconfirm>
                      </el-col>
                    </el-row>
                  </li>
                  <div class="buttons no-center">
                    <el-button @click="addPlain">+ 增加计划</el-button>
                  </div>
                </ul>
              </el-form-item>
            </el-col>
            <!-- <el-form-item label="原因补充" prop="reasonMsg">
                <el-input v-model="ruleForm.reasonMsg" type="textarea" resize="none" :rows="4" class="input" />
              </el-form-item>
              <el-form-item style="width: 100%" label="固定回访" prop="towDemand">
                <el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949" />
              </el-form-item> -->

            <!-- 默认拉取顾客资料里面的电话 -->
            <!-- <el-form-item style="width: 100%" label="联系电话" prop="customerPhone">
                <el-input v-model="ruleForm.customerPhone" />
              </el-form-item> -->
          </div>
        </el-row>
        <!-- <el-row class="information" style="width: 48%">
            顾客相关资料
            <el-row type="flex" class="datas">
              <el-col :span="8">
                <img src="../../../assets/image/newAdd/headPortrait.png" alt="">
              </el-col>
              <el-col :span="16">
                <div>{{ userInfo.nickname }} （No.{{ userInfo.code }}）<i class="el-icon-female" /></div>
                <div>
                  手机：
                  <span v-if="one">{{ userInfo.phone }}</span>
                  <span v-if="!one">{{ userInfo.hidePhone }}</span>
                  <el-button type="text" @click="one = !one">{{
                    one ? "隐藏" : "显示完整"
                  }}</el-button>
                </div>
                <div>
                  身份证：
                  <span v-if="two">{{ userInfo.idNumber }}</span>
                  <span v-if="!two">{{ userInfo.hideIdNumber }}</span>
                  <el-button type="text" @click="two = !two">{{
                    two ? "隐藏" : "显示完整"
                  }}</el-button>
                </div>
                <div style="text-align: right">余额：<span class="color">{{ userInfo.capital }}</span></div>
              </el-col>
            </el-row>
            <el-row>
              <el-row>
                <el-col :span="3">
                  特征信息
                </el-col>
                <el-col :offset="18" :span="3">
                  <el-button type="primary" plain>详情<i class="el-icon-d-arrow-right" /></el-button>
                </el-col>
              </el-row>
              <el-col>
                生日
                <span>{{ userInfo.birthday }}</span>
              </el-col>
              <el-col>
                年龄
                <span>{{ userInfo.age }}</span>
              </el-col>
              <el-col>
                省市
                <span>{{ userInfo.address }}</span>
              </el-col>
              <el-col>
                区县
                <span>{{ userInfo.address }}</span>
              </el-col>
            </el-row>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title"> 归属信息 </template>
                <el-row>
                  <el-row>
                    <el-col :span="10">
                      开发渠道
                      <span>{{ userInfo.property }}</span>
                    </el-col>
                    <el-col :span="10">
                      推荐人
                      <span>{{ userInfo.recommenderName }}</span>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="10">
                      开发人员
                      <span>{{ userInfo.developersName }}</span>
                    </el-col>
                    <el-col :span="10">
                      归属咨询师
                      <span>{{ userInfo.attributionConsultantName }}</span>
                    </el-col>
                  </el-row>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title"> 咨询记录 </template>
                <el-row>
                  <el-col>
                    <el-row v-for="item in customerAdvisorys" :key="item.id">
                      <el-col :span="13">{{ item.advisoryTime }}</el-col>
                      <el-col :span="2">{{ item.advisoryType }}</el-col>
                      <el-col :span="6">{{ item.intentionProject }}</el-col>
                      <el-col :span="3">{{ item.result }}</el-col>
                      <el-col v-if="item.id" :span="3"><a>详情</a></el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title"> 消费记录 </template>
                <el-row>
                  <el-col>
                    <el-row v-for="item in customerConsumes" :key="item.id">
                      <el-col :span="13">{{ item.createdTime }}</el-col>
                      <el-col :span="4">{{ item.projectName }}</el-col>
                      <el-col :span="3">{{ item.price }}</el-col>
                      <el-col :span="4">{{ item.paymentStatus }}</el-col> -->
        <!--                      <el-col v-if="item.id" :span="4"><a>详情</a></el-col>-->
        <!-- </el-row>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title"> 项目记录 </template>
                <el-row>
                  <el-col>
                    <el-row v-for="item in customerProjects" :key="item.id">
                      <el-col :span="13">{{ item.createdTime }}</el-col>
                      <el-col :span="4">{{ item.projectName }}</el-col>
                      <el-col :span="4">{{ item.price }}</el-col>
                      <el-col :span="4" :offset="4">{{
                        item.advisoryTime
                      }}</el-col>
                      <el-col v-if="item.id" :span="4"><a>详情</a></el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title"> 回访记录 </template>
                <el-row>
                  <el-col>
                    <el-row v-for="item in customerReturnVisits" :key="item.id">
                      <el-col :span="13">{{ item.returnVisitDate }}</el-col>
                      <el-col :span="7">{{ item.returnVisitType }}</el-col>
                      <el-col :span="4">{{ item.revisiterName }}</el-col>
                      <el-col v-if="item.id" :span="4"><a>详情</a></el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </el-row> -->
        <!-- </el-row> -->
        <el-row type="flex" class="buttons">
          <!-- <el-col> -->
          <!-- 仅保存，还可以再更改 -->
          <span>
            <el-button class="submitButton" type="primary" @click="submitForm('ruleForm', 1)">保存</el-button>
            <!-- </el-col> -->
            <!-- <el-col> -->
            <!-- 点击后，当次咨询不可再更改 -->
            <el-button class="submitButtons" type="primary" @click="submitForm('ruleForm', 2)">保存并归档</el-button>
            <!-- </el-col> -->
          </span>
        </el-row>
        <el-row>
          <span class="span">归档后不可再更改</span>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, EditorContent } from "tiptap";
import { formatDate } from "@/api/fifters.js";
import { DictionarySelector } from "@rabbit.do/rabbit";
import { tableColor } from '@/utils/common.js';
import UserInfo from "@/components/UserInformation";
export default {
  name: "Index",
  components: { DictionarySelector, EditorContent, UserInfo },
  filters: {
    formatDate(time) {
      var data = new Date(time);
      return formatDate(data, "yyyy-MM-dd");
    },
  },
  props: {
    modalVisibleData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      propsOption: {
        value: 'id',
        label: 'dataName',
        checkStrictly: true,
      },
      restaurants: [],
      state: '',
      tableColor,
      uploadUrl: window.GLOBAL.FILE_SERVER + "/api/v1/base/attach/data/upload/attach",
      modalShow: false,
      loading: false,
      type: [],
      value: true,
      value1: "",
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      demandData: [], // 添加咨询时主次需求
      ruleForm: { result: "成交", opinion: "未见医生" },
      reasonMsg: "",
      userInfo: {},
      one: false,
      two: false,
      triageId: "",
      selectedRow: {},
      projectOptions: [],
      attendingDoctors: [],
      customerAdvisorys: [],
      customerConsumes: [],
      customerProjects: [],
      customerReturnVisits: [],
      demands: [],
      productTableShow: false,
      advisoryId: "",
      suggesContent: `<p>
            顾客诉求：
          </p>
          <P>
            顾客情况：
          </P>
          <P>
            诊断结果：
          </P>`,
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      plainData: [],
      ReturnVisitRules: [],
      rules: {
        treatType: [
          // 就诊类型
          { required: true, message: "请输入原因", trigger: "blur" },
        ],
        // oneDemand: [
        //   // 主要需求
        //   { required: true, message: "请选择主要需求", trigger: "blur" },
        // ],
        result: [
          // 咨询结果
          { required: true, message: "请输入咨询结果", trigger: "blur" },
        ],
        consultTypeName: [
          // 未成交原因
          { required: true, message: "请选择咨询分类", trigger: "change" },
        ],
      },
      interviewTaskDate: "",
      editor: null,
      pickerOptions: {
        disabledDate(time) {
          const times = Date.now() - 24 * 60 * 60 * 1000;
          return time.getTime() < times;
        },
      },
    };
  },
  watch: {
    modalVisibleData: {
      handler() {
        this.getCustomer();
      },
    },
  },
  beforeDestroy() {
    this.destroyPopup();
  },
  mounted() {
    this.productfindall();
  },
  methods: {
    handleChange(val, aa) {
      if (val && val.length > 0) {
        const nameList = [];
        let list = this.options;
        val.forEach(item => {
          list.forEach(json => {
            if (item === json.id) {
              nameList.push(json.dataName);
              if (json.children) list = json.children;
            }
          });
        });
        if (!this.ruleForm.demandDtos) {
          this.ruleForm.demandDtos = [{
            'projectName': nameList.join(">"),
            'projectId': val.join(","),
            'lastProjectId': val[val.length - 1],
            'adviserId': this.ruleForm.adviserId,
            'customerCode': this.ruleForm.customerCode,
            'customerId': this.ruleForm.customerId,
            'customerName': this.ruleForm.customerName,
            'customerPhone': this.ruleForm.customerPhone,
            'demandSort': aa,
          }];
          return false;
        }
        let bools = false;
        this.ruleForm.demandDtos.forEach((item, i) => {
          if (item.demandSort === aa) {
            bools = true;
            const changeItem = {
              'projectName': nameList.join(">"),
              'projectId': val.join(","),
              'lastProjectId': val[val.length - 1],
              'adviserId': this.ruleForm.adviserId,
              'customerCode': this.ruleForm.customerCode,
              'customerId': this.ruleForm.customerId,
              'customerName': this.ruleForm.customerName,
              'customerPhone': this.ruleForm.customerPhone,
              'demandSort': aa,
            };
            this.ruleForm.demandDtos[i] = changeItem;
          }
        });
        if (!bools) {
          this.ruleForm.demandDtos.push({
            'projectName': nameList.join(">"),
            'projectId': val.join(","),
            'lastProjectId': val[val.length - 1],
            'adviserId': this.ruleForm.adviserId,
            'customerCode': this.ruleForm.customerCode,
            'customerId': this.ruleForm.customerId,
            'customerName': this.ruleForm.customerName,
            'customerPhone': this.ruleForm.customerPhone,
            'demandSort': aa,
          });
        }
      }
    },
    deteleProduct(item) {
      this.ruleForm.sbDtos.forEach((element, i) => {
        if (element.id === item.id) {
          this.ruleForm.sbDtos.splice(i, 1);
        }
      });
    },
    handleProduct(item) {
      this.ruleForm.sbDtos.push({
        'intentionProject': item.name,
        'intentionProjectId': item.id,
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },
    addPlain() { // 增加计划
      this.plainData.push({
        rebackTime: '',
        returnName: this.ruleForm.attendingDoctor,
        returnId: this.ruleForm.attendingDoctor,
      },);
    },
    deletePlain(i) { // 删除计划
      this.plainData.splice(i, 1);
    },
    getVisitRuleList() {
      this.$api["doctor/consulting/allVisitRuleList"]({ query: { type: '未成交回访' }}).then((res) => {
        if (res.code !== 200) return this.$message.error("查询列表回访规则失败");
        this.ReturnVisitRules = res.data;
        this.ReturnVisitRules.forEach(item => {
          const dates = new Date(new Date(item.createdTime).valueOf() + 24 * 60 * 60 * 1000 * Number(item.returnDay));
          const year = dates.getFullYear();
          const month = dates.getMonth() + 1;
          const day = dates.getDate();
          const rebackTime = year + "-" + month + "-" + day;
          this.$set(item, 'rebackTime', rebackTime);
        });
      });
    },
    handlechange() {
      // this.$set(this.ruleForm, 'faceDoctor', this.ruleForm.attendingDoctor);
    },
    loadDepDatas(id) {
      // this.fetchProduct();
      this.fetchAdvisType();
      this.fetchHospital();
      this.fetchAllUsr();
      this.getCustomer();
      this.fetchDetail(id);
      this.findCustomerAdvisoryLog();
      this.getProjectData();
      this.findCustomerConsumeLog();
      this.findCustomerProjectLog();
      this.findCustomerReturnVisitLog();
      this.getTreeProject();
    },
    advisory(row, triageId, advisoryId) {
      // 首次咨询
      this.plainData = [];
      this.selectedRow = row;
      this.advisoryId = advisoryId;
      this.triageId = triageId;
      this.modalShow = true;
      this.loadDepDatas(this.triageId);
      this.getReasons();
      this.getVisitRuleList();
    },
    getReasons() {
      this.$api["seting/siteConsul/getDicoptList"]({
        query: { dictionaryId: "785887304244789248" },
      }).then((res) => {
        if (res.code !== 200) return this.$message.error("查询不成交原因失败");
        this.type = res.data.optionList;
      });
    },
    handleSelectProject(item) {
      // 调整意向项目
      this.ruleForm.intentionProject = item.name;
      this.ruleForm.intentionProjectId = item.id;
      this.$forceUpdate();
    },
    async getProjectData() {
      // 意向项目
      const projectData = await this.$api["reception/triage/findAll"]();
      if (projectData.code === 200) {
        this.projectOptions = projectData.data;
      }
    },
    selectAttendingDoctor(val) {
      // 选择主治医生
      this.ruleForm.attendingDoctor = val.label;
      this.$forceUpdate();
    },
    selectAttendingFaceDoctor(val) {
      // 更改面诊医生
      this.ruleForm.faceDoctor = val.label;
      this.$forceUpdate();
    },
    async findCustomerAdvisoryLog() {
      // 顾客咨询记录
      this.list = [];
      const res = await this.$api["customer/customers/findAllByCustomerId"]({
        id: this.selectedRow.customerId,
      });
      if (res.code !== 200) return;
      this.customerAdvisorys = res.data;
    },
    async findCustomerConsumeLog() {
      // 顾客消费记录
      this.list = [];
      const res = await this.$api["customer/customers/orderListDetails"]({
        customerId: this.selectedRow.customerId,
      });
      if (res.code !== 200) return;
      this.customerConsumes = res.data;
    },
    async productfindall() {
      // 所有项目
      const res = await this.$api[
        "data/projects/productfindall"
      ]({});
      if (res.code !== 200) return;
      this.restaurants = res.data;
    },
    async findCustomerProjectLog() {
      // 顾客项目记录
      this.list = [];
      const res = await this.$api[
        "reception/subscribe/customerIdAllByOrderList"
      ]({
        customerId: this.selectedRow.customerId,
      });
      if (res.code !== 200) return;
      this.customerProjects = res.data;
    },
    async findCustomerReturnVisitLog() {
      // 顾客回访记录
      this.list = [];
      const res = await this.$api["customer/customers/returnVisitDetails"]({
        customerId: this.selectedRow.customerId,
      });
      if (res.code !== 200) return;
      this.customerReturnVisits = res.data;
    },
    destroyPopup() {
      if (this.popup) {
        this.popup[0].destroy();
        this.popup = null;
      }
    },
    fetchDetail(id) {
      // 获取订单详情
      console.log("8888");
      this.loading = true;
      const api = "doctor/consulting/triageList";
      this.$api[api]({ id }).then((res) => {
        if (res.code !== 200) return;
        this.loading = false;
        this.ruleForm = res.data;
        this.$set(this.ruleForm, 'result', "成交");
        this.$set(this.ruleForm, 'opinion', "未见医生");
        if (!this.ruleForm.sbDtos) {
          this.$set(this.ruleForm, 'sbDtos', []);
        }
        this.ruleForm.intentionProject = this.ruleForm.intentCaseName;
        // this.ruleForm.faceDoctor = this.ruleForm.attendingDoctor;
        this.ruleForm.intentionProjectId = this.ruleForm.intentCaseId;
        this.ruleForm.attendingDoctor = res.data.faceDoctorName;
        this.$set(this.ruleForm, 'faceDoctor', this.ruleForm.attendingDoctor);
        this.$set(this.ruleForm, 'loseReasons', []);
        this.advisoryTemplate();
      });
    },
    advisoryTemplate() {
      // 获取当前医院的咨询模板
      if (this.editor) {
        this.editor.destroy();
      }
      if (this.advisoryId) {
        const id = this.advisoryId;
        this.$api["doctor/consulting/advisoryList"]({ id }).then((res) => {
          if (res.code !== 200) return;
          Object.assign(this.ruleForm, res.data);
          // this.ruleForm.oneDemand = ['1352447332221849701', '1354356053952827392'];
          if (this.ruleForm.oneDemand) this.ruleForm.oneDemand = this.ruleForm.oneDemand.split(',');
          if (this.ruleForm.towDemand) this.ruleForm.towDemand = this.ruleForm.towDemand.split(',');
          if (this.ruleForm.threeDemand) this.ruleForm.oneDethreeDemandmand = this.ruleForm.threeDemand.split(',');
          this.suggesContent = this.ruleForm.advisoryInfo;
          this.demandChangeValue(1, this.ruleForm.oneDemand);
          this.demandChangeValue(2, this.ruleForm.towDemand);
          this.demandChangeValue(3, this.ruleForm.threeDemand);
          this.$set(this.ruleForm, "advisoryInfo", this.suggesContent);
          this.editor = new Editor({
            onUpdate: ({ state, getHTML, getJSON, transaction }) => {
              this.$set(this.ruleForm, "advisoryInfo", getHTML());
            },
            // content: this.suggesContent,
          });
        });
      } else {
        this.$api["seting/consulting/HisAdvisoryTemplate"]({}).then((res) => {
          if (res.code !== 200) return;
          this.suggesContent = res.data.template;
          this.$set(this.ruleForm, "advisoryInfo", this.suggesContent);
          this.editor = new Editor({
            onUpdate: ({ state, getHTML, getJSON, transaction }) => {
              this.$set(this.ruleForm, "advisoryInfo", getHTML());
            },
            content: this.suggesContent,
          });
        });
      }
    },
    async addConsultation() {
      // 点击发起面诊interviewTask
      this.loading = true;
      const res = await this.$api["doctor/consulting/interviewTask"](
        this.ruleForm
      );
      if (res.code !== 200) return this.$message.error("发起面诊失败！");
      let url = "doctor/consulting/addProduct";
      if (this.advisoryId) {
        url = "doctor/consulting/UpdateAdvisory";
        this.ruleForm.id = this.advisoryId;
      }
      this.$set(this.ruleForm, "triageId", this.triageId);
      this.$api[url]({
        ...this.modalVisibleData,
        ...this.ruleForm,
        // demandDtos: this.demandData,
      }).then((res) => {
        if (res.code !== 200) return this.$msg.error("新增咨询失败");
        this.$message.success("保存成功");
        if (res.data.id) {
          this.advisoryId = res.data.id;
        }
      });
      this.$message.success("发起面诊成功");
      const date = new Date();
      this.interviewTaskDate =
        date.getFullYear() +
        "-" +
        (date.getMonth() + 1) +
        "-" +
        date.getDate() +
        " " +
        date.getHours() +
        ":" +
        date.getMinutes() +
        ":" +
        date.getSeconds();
      this.loading = false;
    },
    async getCustomer() {
      // 查询顾客信息
      const res = await this.$api["department/order/customer"]({
        id: this.selectedRow.customerId,
      });
      if (res.code !== 200) return this.$message.error("查询顾客信息失败！");
      this.userInfo = res.data;
      this.$set(
        this.userInfo,
        "hidePhone",
        this.userInfo.phone
          ? this.userInfo.phone.slice(0, 3) +
          "****" +
          this.userInfo.phone.slice(7, 11)
          : ""
      );
      this.$set(
        this.userInfo,
        "hideIdNumber",
        this.userInfo.idNumber
          ? this.userInfo.idNumber.slice(0, 3) +
          "****" +
          this.userInfo.idNumber.slice(16, 18)
          : "*******"
      );
    },
    async fetchHospital() {
      // 获取医生
      const res = await this.$api["doctor/consulting/hisusrjobSelect"]({
        hospitalJobName: "主治医生",
      });
      if (res.code !== 200) return this.$message.error("查询医生失败！");
      this.attendingDoctors = [];
      res.data.forEach((item, i) => {
        this.attendingDoctors[i] = { value: item.id, label: item.usrName };
      });
    },
    async fetchAllUsr() {
      // 获取全部医院人员
      const res = await this.$api["doctor/consulting/getAllUsr"]({});
      if (res.code !== 200) return this.$message.error("查询人员失败！");
      this.$set(this.ruleForm, "getAllUsr", res.data);
    },
    handleList(response, file, fileList) {
      const list = [];
      fileList.forEach((item) => {
        list.push(item.response.data.id);
      });
      this.$message.success("上传成功");
      // this.ruleForm.attachUrl = list.join(",");
      this.$set(this.ruleForm, "attachUrl", list.join(","));
      console.log(this.ruleForm.attachUrl);
    },
    fetchProduct() {
      this.$api["doctor/consulting/productListPull"]({
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      }).then((res) => {
        if (res.code !== 200) return;
        this.$set(this.ruleForm, "regions", res.data.result);
      });
    },
    getTreeProject() { // 获取意向项目的多级联动数据
      this.$api["data/goods/treeList"]({ dataType: '项目类' }).then((res) => {
        if (res.code !== 200) return;
        this.options = res.data;
      });
    },
    fetchAdvisType() {
      this.$api["seting/consulting/consultPage"]({
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      }).then((res) => {
        if (res.code !== 200) return;
        this.demands = res.data.result;
      });
    },
    demandChangeValue(number, id) {
      const regions = this.demands;
      if (number === 1 && id) {
        this.dataSome(id, number, regions);
      } else if (number === 2 && id) {
        this.dataSome(id, number, regions);
      } else if (number === 3 && id) {
        this.dataSome(id, number, regions);
      }
      this.$forceUpdate();
    },
    rebackManChangeValue(id, i) {
      // 选择回访人
      this.ruleForm.getAllUsr.forEach(item => {
        if (item.id === id) {
          this.plainData[i].returnName = item.usrName;
        }
      });
      // this.ruleForm.rebackMan = val.usrName;
    },
    dataSome(id, number, regions) {
      // let is = 0;
      // const bool = this.demandData.some((item, i) => {
      //   is = i;
      //   return this.demandData[i].demandSort === number;
      // });
      // bool
      //   ? (this.demandData[is] = this.demandDtos(id, regions, number))
      //   : this.demandData.push(this.demandDtos(id, regions, number));
    },
    init() {
      this.modalShow = true;
    },
    modalClose() {
      this.ruleForm = {};
      this.modalShow = false;
      if (this.editor) {
        this.editor.destroy();
      }
      this.$refs["ruleForm"].resetFields();
    },
    submitForm(formName, number) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          let url = "";
          let msg = "";
          if (number === 1) {
            url = "doctor/consulting/addProduct";
            if (this.advisoryId) {
              url = "doctor/consulting/UpdateAdvisory";
              this.ruleForm.id = this.advisoryId;
            }
            msg = "保存成功";
          } else {
            url = "doctor/consulting/addProductEnd";
            msg = "结束咨询成功";
          }
          this.$set(this.ruleForm, "triageId", this.selectedId);
          this.$set(this.ruleForm, "remedyType", this.ruleForm.treatType);
          this.$set(this.ruleForm, "consultantId", this.ruleForm.adviserId);
          this.$set(this.ruleForm, "consultantName", this.ruleForm.adviserName);
          this.$set(this.ruleForm, "receiveId", this.ruleForm.accepterId);
          this.$set(this.ruleForm, "receiveName", this.ruleForm.accepterName);
          this.$set(this.ruleForm, "triageId", this.triageId);
          // 咨询表就诊类型
          this.$set(this.ruleForm, "remedyType", this.ruleForm.treatType);
          this.$set(this.ruleForm, "customerSex", this.ruleForm.sex);
          // this.$set(this.ruleForm, "getAllUsr", []);
          // this.$set(this.ruleForm, "demandDtos", []);
          this.$set(this.ruleForm, "regions", []);
          this.$set(this.ruleForm, "simpleDtoList", this.plainData);
          if (this.ruleForm.oneDemand) this.$set(this.ruleForm, "oneDemand", this.ruleForm.oneDemand.toString());
          if (this.ruleForm.towDemand) this.$set(this.ruleForm, "towDemand", this.ruleForm.towDemand.toString());
          if (this.ruleForm.threeDemand) this.$set(this.ruleForm, "threeDemand", this.ruleForm.threeDemand.toString());
          this.ReturnVisitRules.forEach(item => {
            item.returnId = item.id;
            this.ruleForm.simpleDtoList.push(item);
          });
          this.ruleForm.getAllUsr.forEach(item => {
            this.ruleForm.simpleDtoList.forEach(element => {
              if (item.usrName === element.returnName || item.id === element.returnId) {
                element.returnName = item.usrName;
                element.returnId = item.id;
              }
            });
          });
          this.$api[url]({
            ...this.modalVisibleData,
            ...this.ruleForm,
            // demandDtos: this.demandData,
          }).then((res) => {
            if (res.code !== 200) return this.$msg.error("新增咨询失败");
            this.$emit("success");
            this.loading = false;
            this.modalShow = false;
            this.$message.success(msg);
          });
        } else {
          return false;
        }
      });
    },
    async handleRemove(file, fileList) {
      const id = file.response.data.id;
      const res = await this.$api["doctor/consulting/deleteImage"]({
        fileId: id,
      });
      if (res.code !== 200) return false;
      this.$message.success("删除成功");
    },
    fileRemove(file, fileList) {
      const list = [];
      fileList.forEach((item) => {
        list.push(item.response.data.id);
      });
      this.ruleForm.attachUrl = list.join(",");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // demandDtos(projectId, regions, number) {
    //   let obj = {};
    //   regions.forEach((r) => {
    //     if (projectId === r.id) {
    //       obj = { demandSort: number, projectId: r.id, projectName: r.name };
    //     }
    //   });
    //   return obj;
    // },
    createBill() {
      // 去开单
      this.submitForm("ruleForm", 1);
      this.modalClose();
      this.$parent.Billing(this.selectedRow);
    },
    createRecharge() {
      // 去充值
      this.submitForm("ruleForm", 1);
      this.modalClose();
      this.$parent.seeRecharge(this.selectedRow.customerId);
    },
  },
};
</script>

<style scoped lang="scss">
// .top {
//   display: flex;
// }
// .buttons {
//   padding: 2px 4px !important;
//   height: 32px;
//   margin-left: 10px;
//   background: rgb(81, 204, 194);
//   color: #fff;
// }

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.information {
  line-height: 40px;
}
.buttons {
  display: flex;
  justify-content: center;
  button {
    width: 140px;
    height: 40px;
  }
}
.no-center{
  justify-content: left;
}
/deep/.el-collapse-item__header {
  border-bottom: none !important;
}
.el-collapse {
  border-bottom: none;
  border-top: none;
}
.box {
  border: 1px solid #d3dff7;;
  min-height: 90px;
  padding: 5px;
  height: 120px;
  overflow-y: scroll;
  li {
    margin: 0 10px;
  }
}
.input /deep/textarea{
  border: 1px solid #d3dff7;
  width: 89%;
}
.el-input__inner {
  border: 1px solid #aaaaaa;
  min-height: 90px;
  padding: 5px;
  width: 89%;
  li {
    margin: 0 10px;
  }
}
$color-black: #000000;
$color-white: #ffffff;
$color-grey: #dddddd;
.mention {
  background: rgba($color-black, 0.1);
  color: rgba($color-black, 0.6);
  font-size: 0.8rem;
  font-weight: bold;
  border-radius: 5px;
  padding: 0.2rem 0.5rem;
  white-space: nowrap;
}
/deep/.ProseMirror p {
  margin: 0 !important;
}
.color{
  color: #f67c6e;
}
/deep/.el-input--small input{
  border: 1px solid #d3dff7;
  border-radius: 5px;
}
/deep/.el-input--small input:hover{
  border: 1px solid #d3dff7;
  border-radius: 5px;
}
.datas{
  box-shadow: rgba(0,0,0,.3) 0px 0px 10px;
}
.el-col-8{
  img{
  width: 100%;
  border-radius: 50%;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  }
}
.el-icon-female{
  transform: rotate(45deg);
  color: #f77464;
}
.span{
  color: #aaaaaa;
  display: block;
  font-size: 12px;
  padding: 10px 0 0 344px;
}
ul{
  // margin-top: 20px;
  li{
    margin: 0 !important;
    .el-col-8{
      display: flex;
      margin-left: -50px;
      margin-right: 20px;
    }
  }
}

.submitButton,.submitButtons{
  width: 150px !important;
  height: 30px !important;
  background: #0278DC;
  border-radius: 4px;
  border: none;
  color:#fff;
}
.submitButton,.submitButtons{
  width: 150px !important;
  height: 30px !important;
  background: #0278DC !important;
  border-radius: 4px !important;
  color:#fff !important;
}
.submitButton:hover{
  background: #4791d1 !important;
}
.submitButtons{
  background: #EFF3FB !important;
  color: #0278DC !important;
}
.submitButtons:hover{
  background: #46a6ff !important;
  color: #fff !important;
}

/deep/.el-upload--picture-card{
  border: 1px dashed #D3DFF7 !important;
  i{
    color: #D3DFF7
  }
}
.el-table{
  margin-top: 0 !important;
}
/deep/.box{
  height: 180px;
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
/deep/ .is-true .el-upload--picture-card{
  width: 50px;
  height: 50px;
  line-height: 55px;
}
</style>
